package com.xiaoqi.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoqi.constant.MessageConstant;
import com.xiaoqi.pojo.Result;
import com.xiaoqi.service.MemberService;
import com.xiaoqi.service.OrderService;
import com.xiaoqi.service.ReportService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author PC
 * creationTime: 2022/11/25 16:25
 */
@RequestMapping("/report")
@RestController
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private OrderService orderService;

    @Reference
    private ReportService reportService;


    /**
     * 线图显示每个阶段的会员数量
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport(){
        //返回两个列表，一个日期月份，一个会员人数的
        HashMap<String, Object> map = new HashMap<>();
        //获取日历类
        Calendar calendar = Calendar.getInstance();
        //储存年月
        List<String> months = new ArrayList<>();
        //准备数据
        calendar.add(Calendar.YEAR,-1);
        for (int i = 0; i < 12; i++) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            months.add(sdf.format(calendar.getTime()));
            calendar.add(Calendar.MONTH,+1);
        }
        //储存会员人数
        List<Integer> memberCount = memberService.findMemberCountBeforeDate(months);
        //将列表加入map
        map.put("months",months);
        map.put("memberCount",memberCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }

    /**
     * 通过套餐id分组查询每个套餐被预约的个数以及名字（饼状图）
     * @return
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){
        //页面需要list套map
        List<Map> list = orderService.findGroupBySetmealID();
        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,list);
    }

    /**
     *运营数据的查询包括会员，预约与套餐
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        Map<String, Object> map = reportService.getBusinessReportData();
        return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
    }


    /**
     * 处理用户点击到处excel
     * @return
     */
    @GetMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletResponse response, HttpServletRequest request) throws IOException {
        //获取模板全路径名称
        String ImportFileName = request.getSession().getServletContext().getRealPath("/ExeclTemp/report_template.xlsx");
//        System.out.println(ImportFileName);
//        String OutPutFileName = "";
        //创建文件读取流
        InputStream inputStream = new FileInputStream(new File(ImportFileName));
        //创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        //创建Sheet
        Sheet sheet = workbook.getSheetAt(0);
        Map<String, Object> map = reportService.getBusinessReportData();
        //创建行
        //日期
        Row row = sheet.getRow(2);
        row.getCell(5).setCellValue(map.get("reportDate").toString());
        //会员数据统计
        row = sheet.getRow(4);
        row.getCell(5).setCellValue(map.get("todayNewMember").toString());
        row.getCell(7).setCellValue(map.get("totalMember").toString());

        row = sheet.getRow(5);
        row.getCell(5).setCellValue(map.get("thisWeekNewMember").toString());
        row.getCell(7).setCellValue(map.get("thisMonthNewMember").toString());
        //预约到诊数据统计
        row = sheet.getRow(7);
        row.getCell(5).setCellValue(map.get("todayOrderNumber").toString());
        row.getCell(7).setCellValue(map.get("todayVisitsNumber").toString());

        row = sheet.getRow(8);
        row.getCell(5).setCellValue(map.get("thisWeekOrderNumber").toString());
        row.getCell(7).setCellValue(map.get("thisWeekVisitsNumber").toString());

        row = sheet.getRow(9);
        row.getCell(5).setCellValue(map.get("thisMonthOrderNumber").toString());
        row.getCell(7).setCellValue(map.get("thisMonthVisitsNumber").toString());

        //热门套餐
        List<Map> setmeals = (List<Map>) map.get("hotSetmeal");

        for (int i = 0; i < setmeals.size() ; i++) {
            row = sheet.getRow(i+12);
            row.getCell(4).setCellValue(setmeals.get(i).get("name").toString());
            row.getCell(5).setCellValue(setmeals.get(i).get("setmeal_count").toString());
            row.getCell(6).setCellValue(setmeals.get(i).get("proportion").toString());
            row.getCell(7).setCellValue(setmeals.get(i).get("remark").toString());
        }


        String fileName = "运营数据统计"+System.currentTimeMillis()+".xlsx";

        try{
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            OutputStream os = response.getOutputStream();
            workbook.write(os);
            os.flush();
            os.close();
        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }






    public static void main(String[] args) {
        
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.YEAR,-1);
////        System.out.println(calendar.getTime());
//        for (int i = 0; i <12; i++) {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
//            System.out.println(sdf.format(calendar.getTime()));
//            calendar.add(Calendar.MONTH,+1);
//        }


    }
}
